import { updateCule } from "../api/system"
import { getUserInfo, wxLogin } from "../api/user"
import { JudgmentExpiration } from "./judgmentExpiration"
import { CuleProps } from "./type"
import { getMapMax, mapToArray } from "./util"

class Login {
  JudgmentExpirationInstance = new JudgmentExpiration()
  isExpire = false
  constructor() {

  }
  //定时任务，token 过期前重新获取token
  timerTask() {
    const expireTime = wx.getStorageSync('expire') || 0
    const loginTime = wx.getStorageSync('loginTime') || 0
    this.JudgmentExpirationInstance.init(expireTime, loginTime, () => {
      //倒计时结束 重新获取token
      this.getToken().then(() => {
        //获取到token后，重新调用定时任务
        this.timerTask()
      })
    })
  }

  getToken() {
    return new Promise((resolve) => {
      wx.login({
        success: res => {
          console.log('login', res.code)
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          wxLogin(res.code).then(res => {
            //通过返回的数据是否存在token 判断用户是否新用户
            if ('accessToken' in res.result) {
              //老用户
              //获取用户信息 保存
              console.log('老用户')
              this.oldUser(res)
              resolve({ result: res.result, userExist: true })
            } else {
              //新用户
              console.log('新用户')
              this.newUser(res)
              resolve({ result: res.result, userExist: false })
            }
          })
        },
      })
    })
  }

  //新用户
  newUser(res: any) {
    wx.setStorageSync('openId', res.result.openId)
    wx.setStorageSync('sessionKey', res.result.sessionKey)
  }
  //老用户
  oldUser(res: any) {
    wx.setStorageSync('sessionKey', res.result.sessionKey)
    wx.setStorageSync('accessToken', res.result.accessToken)
    wx.setStorageSync('refreshToken', res.result.refreshToken)
    wx.setStorageSync('expire', res.result.expire)
    //保留首次登录的时间
    wx.setStorageSync('loginTime', new Date().getTime() / 1000)
  }
  userInfo() {
    return new Promise((resolve) => {
      getUserInfo().then(res => {
        wx.setStorageSync('userInfo', res.result)
        resolve(res.result)
      })
    })
  }
  removeStorage() {
    wx.removeStorageSync('accessToken')
    wx.removeStorageSync('refreshToken')
    wx.removeStorageSync('expire')
    wx.removeStorageSync('loginTime')
    wx.removeStorageSync('openId')
    wx.removeStorageSync('sessionKey')
    wx.removeStorageSync('userInfo')
    wx.setStorageSync('loginStatus', false)
  }
  updateCule() {
    let app = getApp()
    const userInfo = wx.getStorageSync('userInfo') || ''
    console.log('dataCollection', app.globalData.dataCollection)

    const data: CuleProps = {
      "areaName": getMapMax(app.globalData.dataCollection.region),
      "cityName": getMapMax(app.globalData.dataCollection.city),
      "customerId": userInfo && userInfo.id,
      "customerName": userInfo && userInfo.nickname,
      "dataSource": '6',
      "lastViewedTime": app.globalData.dataCollection.leaveTime,
      "phone": userInfo && userInfo.phone,
      "schoolName": wx.getStorageSync('currentDrivingSchool').shortName || '',
      "storeName": '',
      "viewedClassName": mapToArray(app.globalData.dataCollection.class).join(','),
      "systemSource": 2,
      "schoolId": wx.getStorageSync('currentDrivingSchool').id,
      "referrerName": '',
      "referrerPhone": ''
    }
    userInfo && updateCule(data)
  }
  init() {
    //用户进入小程序，根据过期时间判断登录是否过期
    //获取本地存储的过期时间及登录时间
    const expireTime = wx.getStorageSync('expire') || 0
    const loginTime = wx.getStorageSync('loginTime') || 0
    this.isExpire = this.JudgmentExpirationInstance.expire(expireTime, loginTime)
    if (this.isExpire) {
      console.log('token过期')
      //过期，删除本地信息
      this.removeStorage()
    } else {
      console.log('token未过期')
      //没有过期，开启定时器
      this.timerTask()
    }
  }
}

export const loginInstance = new Login()